#include "actiontablewidget.h"

#include <QDebug>
#include <QDropEvent>

ActionTableWidget::ActionTableWidget(QWidget *parent)
    : QTableWidget(parent)
{
}

/*
 * @info: 虽然可能不会有人这样做，但是横向拖动，超出现在表格外时，会被移动到最后行
 */
void ActionTableWidget::dropEvent(QDropEvent *event)
{
    QModelIndex index;
    qDebug() << "index: " << index.row();

    if(viewport()->rect().contains(event->pos()))
    {
        index = indexAt(event->pos());
    }

    qDebug() << "## index:" << index;

    int rowDst = index.row();
    int rowSrc = currentRow();

    // 实际不拖出表格范围，此时均默认移动当前行到表格最底部
    if(-1 == rowDst)
    {
        rowDst = rowCount();
    }
    else
    {
        // 向上拖动，因为是先插入行，所以源行行号要 +1，向上拖动则源行号不变
        rowSrc = (rowSrc > rowDst ? rowSrc + 1 : rowSrc);	// 向上拖动
        // 向下拖动，因
        rowDst = (rowSrc < rowDst ? rowDst + 1 : rowDst);	// 向下拖动
    }

    // 先插入行，再复制行，再删除行
    insertRow(rowDst);
    for(int i = 0; i < columnCount(); ++i)
    {
        setItem(rowDst, i, takeItem(rowSrc, i));
    }
    // 注意：设置选中在删除之前
    selectRow(rowDst);
    removeRow(rowSrc);
}

int ActionTableWidget::position(QPoint pos, QRect rect, QModelIndex &index)
{
    int r = QAbstractItemView::OnViewport;
    int margin = 2;

    if(pos.y() - rect.top() <  margin)
    {
        r = QAbstractItemView::AboveItem;
    }
    else if(rect.bottom() - pos.y() < margin)
    {
        r = QAbstractItemView::BelowItem;
    }
    else if(rect.contains(pos, true))
    {
        r = QAbstractItemView::OnItem;
    }

    if((r == QAbstractItemView::OnItem)
    && !(model()->flags(index) & Qt::ItemIsDropEnabled))
    {
        r = (pos.y() < rect.center().y())
            ? QAbstractItemView::AboveItem : QAbstractItemView::BelowItem;
    }

    return r;
}

bool ActionTableWidget::droppingOnItself(QDropEvent *event, QModelIndex& index)
{
    int dropAction = event->dropAction();

    if(dragDropMode() == QAbstractItemView::InternalMove)
    {
        dropAction = Qt::MoveAction;
    }

    if(event->source() == this
    && event->possibleActions() & Qt::MoveAction
    && dropAction == Qt::MoveAction)
    {
        QModelIndexList selectedIndexes = this->selectedIndexes();
        QModelIndex child = index;
        while(child.isValid() && child != rootIndex())
        {
            if(-1 != selectedIndexes.indexOf(child))
            {
                return true;
            }
            child = child.parent();
        }
    }

    return false;
}
